package ilincar.systemcore.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;

import com.google.gson.Gson;
import com.ilincar.utils.IlincarUrls;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;

import ilincar.entity.BindEntity;
import ilincar.systemcore.App;
import ilincar.systemcore.ddpush.DDPushClientReceiver;
import ilincar.systemcore.ddpush.OnDDPushListener;
import ilincar.systemcore.location.LocationMessage;
import ilincar.systemcore.model.CoreReceiver;
import ilincar.systemcore.model.SystemState;
import ilincar.systemcore.model.WxMeetPersion;
import ilincar.systemcore.net.IlincarRequest;
import ilincar.systemcore.net.IlincarUtils;
import ilincar.systemcore.sim.SimManager;
import ilincar.systemcore.tool.ILog;
import ilincar.systemcore.util.SpUtil;
import ilincar.utils.IlincarAction;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ilincar on 2016/12/9.
 */

public class CoreService extends Service implements OnDDPushListener {

    private final String TAG = "CoreService";

    private CoreReceiver mCoreReceiver = null;

    //10进制的MAC地址
    private String mIntMacAddress = "";

    //当获取不到MAC地址的时候，用此方法去打开WIFI，然后获取MAC地址
    private WifiManager mWifiManager = null;

    private IBinder mBinder = new ServiceBinder();

    private SimManager mSimManager = null;

    private String mIpAddress = "";

    private LocationMessage mLocationMessage = null;

    private SystemState mSystemState = null;

    //ddPUsh 从外部接收广播
    private DDPushClientReceiver mDDPushClient = null;

    private WxMeetPersion mWxMeetPersion = null;

    private App mApp = null;

    private Context mCtx = null;

    public class ServiceBinder extends Binder {
        public CoreService getService() {
            return CoreService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ILog.i("onCreate");
        // mApp = (App) this.getApplicationContext();
        mApp = (App) this.getApplication();
        mCtx = this;
        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

        //系统的一些相关状态，如WIFI,蓝牙等
        mSystemState = new SystemState(this);
        mSystemState.start();

        //外部广播接收
        mCoreReceiver = new CoreReceiver(this);
        mCoreReceiver.registerReceiver();

        //DDPUSH广播接收
        mDDPushClient = new DDPushClientReceiver(this);
        mDDPushClient.setDdPushListener(this);
        mDDPushClient.registerReceiver();

        //SIM卡信息管理类
        mSimManager = new SimManager(this);

        //位置信息
        mLocationMessage = new LocationMessage(this);

        //微信接人，预导航
        mWxMeetPersion = new WxMeetPersion(this);

        // 若有网就启动,没有网络时打火启动
        if (IlincarUtils.hasNetwork(this)) {
            start();
        }
    }

    public void start() {

        mSystemState.start();
        new HttpTask().execute();
        //开始获取城市位置信息
        mLocationMessage.start();
        //上传当前车机位置
        mLocationMessage.uploadLocation();

    }

    public void stop() {
        //获取天气信息，位置信息停止
        mLocationMessage.stop();
        mSystemState.sleep();
    }

    /**
     * 打开了WIFI
     */
    public void wifiOpened() {
        if ("".equals(mIntMacAddress) || null == mIntMacAddress) {
            mIntMacAddress = IlincarUtils.getIntMacAddress(this);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSimManager.stop();
        mLocationMessage.stop();
        mCoreReceiver.unregisterReceiver();
        mDDPushClient.setDdPushListener(null);
        mDDPushClient.unregisterReceiver();
    }

    /**
     * 网络连接
     */
    public void connectedNetwork() {
        start();
    }

    /**
     * 网络断开
     */
    public void disconnectedNetwork() {
        stop();
    }

    @Override
    public void onRequestCarPosition() {
        //请求当前车的位置
        mLocationMessage.uploadLocation();
    }

    /**
     * 预导航
     *
     * @param jsonObject 请求的obd数据, 解析并启动高德，预导航路径
     */
    @Override
    public void onRequestPrenavigation(JSONObject jsonObject) {
        mWxMeetPersion.requestPrenavigation(jsonObject);
    }

    @Override
    public void onReceiveBindData(JSONObject jsonObject) {
        //返回当前绑定数据
        if (jsonObject == null) {
            return;
        }
        Gson gson = new Gson();
        BindEntity bindEntity = gson.fromJson(jsonObject.toString(), BindEntity.class);
        if (bindEntity != null) {
            //ILog.d(TAG, "查询绑定状态 : " + bindEntity.getResultCode() + "; acctime : " + bindEntity.getAccessTime() + " : errormsg = " + bindEntity.getErrorMsg());
            if ("00".equals(bindEntity.getResultCode())) {
                //绑定成功
                if (bindEntity.getData() != null) {
                    Intent intent = new Intent(IlincarAction.ACTION_UPDATE_BIND_STATE);
                    intent.putExtra("account", bindEntity.getData().getAccount());
                    String aid = bindEntity.getData().getAccountId();
                    intent.putExtra("accountId", aid);
                    intent.putExtra("phonename", bindEntity.getData().getPhonename());
                    intent.putExtra("isbind", "".equals(aid) ? false : true);
                    this.sendBroadcast(intent);
                }
            }
        }
    }

    @Override
    public void onRequestOBDData() {
        //请求OBD数据
        Intent intent = new Intent();
        intent.setAction(IlincarAction.ACTION_REMOTE_CAR_CHECK);
        this.sendBroadcast(intent);
    }

    @Override
    public void onRequestTakePhoto() {
        //请求拍照上传
        Intent intent = new Intent();
        intent.setAction(IlincarAction.ACTION_REQUEST_TAKE_PICTURE);
        this.sendBroadcast(intent);
    }

    @Override
    public void onRequestWeiXinAccess(JSONObject jsonObject) {
        //微信接人
        mWxMeetPersion.show(jsonObject);
    }

    @Override
    public void onRequestUploadVideo(JSONObject jsonObject) {
        //请求上传视频
        if(jsonObject == null) {
            mLocationMessage.postAKeyAlarmMessage();
        }
    }

    @Override
    public void onRequestLiveCamera(JSONObject jsonObject) {
        //请求时时视频流
        try {
            if (jsonObject != null && jsonObject.has("isFront")) {
                int cameraId = jsonObject.getInt("isFront");
                Intent intent = new Intent(IlincarAction.ACTION_NOTIFY_LIVE_CAMERA);
                intent.putExtra("cameraId", cameraId);
                this.sendBroadcast(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestStopLiveCamera() {
        //停止时时视频流
        Intent intent = new Intent(IlincarAction.ACTION_NOTIFY_STOP_LIVE_CAMERA);
        this.sendBroadcast(intent);
    }

    /***
     * 网络任务
     */
    private class HttpTask extends AsyncTask<Void, Void, Void> {


        public HttpTask(){
        }

        @Override
        protected Void doInBackground(Void... params) {
            if ("".equals(mIpAddress) || null == mIpAddress) {
                mIpAddress = IlincarUtils.getInetAddress(IlincarUrls.ILINCAR_URL);
            }

            if (mApp != null) {
                if (System.currentTimeMillis() - SpUtil.getLong(mCtx, SpUtil.KEY_PUSH_ID_TIME) > 2 * 60 * 60 * 1000) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ILog.d(TAG, "==upload pushId fanjc==start=");
                    mApp.getRequest().sendPushId();
                    SpUtil.putLong(mCtx, SpUtil.KEY_PUSH_ID_TIME, System.currentTimeMillis());
                }
            }
            return null;
        }
    }
}
